﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using AutoStopApp.Core;
using AutoStopData.Domains;
using AutoStopData.Model;
using Telerik.Web.UI;

namespace AutoStopApp.Controls
{
    public partial class TripList : AjaxUserControl
    {
        private bool DisplayAlsoDeletedRecords
        {
            get
            {
                if (ViewState["DisplayAlsoDeletedRecords"] == null)
                {
                    ViewState["DisplayAlsoDeletedRecords"] = false;
                }
                return (bool)ViewState["DisplayAlsoDeletedRecords"];
            }
            set
            {
                ViewState["DisplayAlsoDeletedRecords"] = value;
            }
        }

        private bool DisplayAlsoOldRecords
        {
            get
            {
                if (ViewState["DisplayAlsoOldRecords"] == null)
                {
                    ViewState["DisplayAlsoOldRecords"] = false;
                }
                return (bool)ViewState["DisplayAlsoOldRecords"];
            }
            set
            {
                ViewState["DisplayAlsoOldRecords"] = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += PageLoad;
            odsTrips.SelectMethod = "Select";
            odsTrips.Inserting += odsTrips_Inserting;
            odsTrips.Selecting += odsTrips_Selecting;
            rgrTrips.PreRender += rgrTrips_PreRender;
            rgrTrips.ItemCreated += rgrTrips_ItemCreated;
        }

        void PageLoad(object sender, EventArgs e)
        {
            AddAjaxSetting(rgrTrips, rgrTrips);
        }

        public static List<RadComboBoxItem> GetAllRegions()
        {
            var countryCodeOrder = new[] { "SK", "CZ", "AT", "DE", "HU" };
            var domainData = Regions.All();
            var comboboxData = new List<RegionLocalized> { new RegionLocalized() };
            foreach (var countryCode in countryCodeOrder)
            {
                string code = countryCode;
                comboboxData.AddRange(domainData.Where(d => d.CountryCode == code));
            }
            comboboxData.AddRange(domainData.Where(d => !countryCodeOrder.Contains(d.CountryCode)));

            var retVal = new List<RadComboBoxItem>();
            foreach (var region in comboboxData)
            {
                String text = String.Empty;
                if (!String.IsNullOrEmpty(region.RegionCode))
                {
                    text = String.Format("({0}) {1}", region.CountryCode, region.LocalizedName);
                }
                retVal.Add(new RadComboBoxItem(text, region.RegionCode));
            }
            return retVal;
        }

        protected void DisplayAlsoDeletedRecordsButtonClick(object sender, EventArgs e)
        {
            DisplayAlsoDeletedRecords = ((RadButton)sender).Checked;
            rgrTrips.Rebind();
        }

        protected void DisplayAlsoOldRecordsButtonClick(object sender, EventArgs e)
        {
            DisplayAlsoOldRecords = ((RadButton)sender).Checked;
            rgrTrips.Rebind();
        }

        protected void rgrTrips_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridCommandItem)
            {
                var commandItem = e.Item as GridCommandItem;

                var DisplayAlsoDeletedRecordsButton = (RadButton)commandItem.FindControl("DisplayAlsoDeletedRecordsButton");
                DisplayAlsoDeletedRecordsButton.Checked = DisplayAlsoDeletedRecords;

                var DisplayAlsoOldRecordsButton = (RadButton)commandItem.FindControl("DisplayAlsoOldRecordsButton");
                DisplayAlsoOldRecordsButton.Checked = DisplayAlsoOldRecords;
            }
        }

        void odsTrips_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            var currentSession = SessionProvider.CurrentSession;
            if (currentSession == null)
            {
                throw new Exception("Musíte byť prihlásený!");
            }
            var trip = e.InputParameters[0] as Trip;
            if (trip != null)
            {
                trip.OwnerId = currentSession.UserId;
            }
        }

        void odsTrips_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            var currentSession = SessionProvider.CurrentSession;
            if (currentSession == null)
            {
                throw new Exception("Musíte byť prihlásený!");
            }
            else
            {
                var userType = UserTypes.GetName(currentSession.User.UserTypeCode);
                e.InputParameters.Add("ownerId", userType == UserTypes.Name.Administrator ? Guid.Empty : currentSession.UserId);
                e.InputParameters.Add("displayAlsoDeletedRecords", DisplayAlsoDeletedRecords);
                e.InputParameters.Add("displayAlsoOldRecords", DisplayAlsoOldRecords);
            }
        }

        void rgrTrips_PreRender(object sender, EventArgs e)
        {
            var grid = sender as RadGrid;
            if (grid != null)
            {
                foreach (GridDataItem dataItem in grid.Items)
                {
                    DateTime deleted;
                    var converted = DateTime.TryParse(dataItem["Deleted"].Text, out deleted);
                    if (converted)
                    {
                        dataItem["EditCommandColumn"].Controls[0].Visible = false;
                        dataItem["DeleteCommandColumn"].Controls[0].Visible = false;
                    }
                }
            }
        }
    }
}